package com.cucn.ingmall.seckill.controller;

import com.cucn.common.utils.R;
import com.cucn.ingmall.seckill.interceptor.LoginUserInterceptor;
import com.cucn.ingmall.seckill.service.SeckillService;
import com.cucn.ingmall.seckill.to.SeckillSkuRedisTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * 秒杀controller
 *
 * @author KouChaoJie
 * @since: 2022/2/14 14:32
 */
@Controller
@Slf4j
public class SeckillController {
    @Resource
    private SeckillService seckillService;

    /**
     * 返回当前时间可以参与的秒杀商品信息
     */
    @ResponseBody
    @GetMapping("/currentSeckillSkus")
    public R getCurrentSeckillSkus() {
        log.info("currentSeckillSkus正在执行");
        List<SeckillSkuRedisTO> seckillSkuRedisTOS = seckillService.getCurrentSeckillSkus();
        return R.ok().setData(seckillSkuRedisTOS);
    }

    /**
     * 根据skuId查询秒杀商品
     */
    @ResponseBody
    @GetMapping("/sku/seckill/{skuId}")
    public R getSkukillInfo(@PathVariable("skuId") Long skuId) {
        SeckillSkuRedisTO seckillSku = seckillService.getSkuSeckillInfo(skuId);
        return R.ok().setData(seckillSku);
    }

    /**
     * 秒杀商品请求
     *
     * @param killId 秒杀的场次及商品
     * @param key    秒杀商品的随机码
     * @param num    秒杀商品的数量
     */
    @GetMapping("/kill")
    public String seckill(@RequestParam("killId") String killId,
                          @RequestParam("key") String key,
                          @RequestParam("num") Integer num,
                          Model model) {
        log.info("用户:{},开始秒杀商品:{}...", LoginUserInterceptor.loginUser.get().getId(), killId);
        //秒杀方法
        String orderSn = null;
        try {
            orderSn = seckillService.kill(killId, key, num);
            log.info("用户:{},秒杀成功...订单号:{}", LoginUserInterceptor.loginUser.get().getId(), orderSn);
        } catch (InterruptedException e) {
            log.error("用户:{},秒杀失败...订单号:{}", LoginUserInterceptor.loginUser.get().getId(), orderSn, e);
        }
        //KouTODO:2022/2/23 10:28 Kou 秒杀商品时，每一个数据都有一个过期时间
        //KouTODO:2022/2/23 10:29 Kou 秒杀后续流程，简化了收货信息.

        model.addAttribute("orderSn", orderSn);
        return "success";
    }
}
